<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
            <div ref="ganttContainer" style="width: 100%; height: 600px"></div>
            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'message': {
            type: [String],
            default: ''
        },
        'projectId': {
            type: [String, Number],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
        'abc': undefined,
        'def': undefined
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)

    const pageParams = [
        { 'name': 'abc', 'dataType': 'STRING' },
        { 'name': 'def', 'dataType': 'STRING' }
    ]
    let setPageParams = () => {
        pageParams.forEach(param => {
            strategyMap[param.dataType](param, route.query[param.name])
        })
    }
    const strategyMap = {
        STRING: (param, paramValue) => {
            if (typeof paramValue === 'undefined') {
                pageParameter_state[param.name] = undefined
                return
            }
            pageParameter_state[param.name] = paramValue
        },
        BOOLEAN: (param, paramValue) => {
            if (typeof paramValue === 'undefined') {
                pageParameter_state[param.name] = undefined
                return
            }
            if ('true' === (paramValue || '').toLowerCase()) {
                pageParameter_state[param.name] = true
            } else if ('false' === (paramValue || '').toLowerCase()) {
                pageParameter_state[param.name] = false
            } else {
                message.error('参数传入错误！类型不匹配！')
            }
        },
        NUMBER: (param, paramValue) => {
            if (typeof paramValue === 'undefined') {
                pageParameter_state[param.name] = undefined
                return
            }
            if (!isNaN(paramValue)) {
                pageParameter_state[param.name] = Number(paramValue)
            } else {
                message.error('参数传入错误！类型不匹配！')
            }
        },
        ARRAY: (param, paramValue) => {
            if (typeof paramValue === 'undefined') {
                pageParameter_state[param.name] = undefined
                return
            }
            if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
                pageParameter_state[param.name] = []
            } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
                try {
                    pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue))
                } catch (error) {
                    console.error('参数解析失败 ', error)
                    message.error('参数解析失败 ', error)
                }
            } else {
                console.error('参数传入错误！类型不匹配！')
                message.error('参数传入错误！类型不匹配！')
            }
        }
    }
    /*** PUBLISH_EXEGESIS ***
 immediateWatch(
 () => route.query,
 () => {
 setPageParams();
 queryUpdateFlag.value++;

 }
 )
 *** PUBLISH_EXEGESIS ***/
    onMounted(() => {
        setPageParams()
    })

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
    import { gantt } from 'dhtmlx-gantt'

    const ganttContainer = ref(null)
    onMounted(() => {

        gantt.config.columns = [
            { name: 'text', label: '任务名称', tree: true, width: 200 },
            { name: 'start_date', label: '开始时间', align: 'center' },
            { name: 'end_date', label: '结束时间', align: 'center' }
        ]
        gantt.config.scale_unit = 'day'
        gantt.config.date_scale = '%Y-%m-%d'
        gantt.config.subscales = []
        gantt.config.scale_height = 40
        gantt.config.row_height = 30
        gantt.config.readonly = true
        console.log(gantt,'        console.log(gantt);');
        // ✅ 添加第二个时间轴：实际进度
        gantt.addTask({
            renderer: {
                render: function (task) {
                    if (!task.actual_start || !task.actual_end) return null
                    const sizes = gantt.getTaskPosition(task, task.actual_start, task.actual_end)
                    const el = document.createElement('div')
                    el.className = 'actual-progress-bar'
                    el.style.cssText = `
          position: absolute;
          left: ${sizes.left}px;
          top: ${sizes.top + 10}px;
          width: ${sizes.width}px;
          height: 10px;
          background-color: #facc15;
          opacity: 0.7;
        `
                    return el
                },
                // 绑定唯一 id
                getId: task => task.id + '_actual'
            }
        })

        // ✅ 初始化
        gantt.init(ganttContainer.value)

        // ✅ 模拟数据
        gantt.parse({
            data: [
                {
                    id: 1,
                    text: '会议任务',
                    start_date: '2025-07-01',
                    end_date: '2025-07-10',
                    actual_start: '2025-07-02',
                    actual_end: '2025-07-07',
                    open: true
                },
                {
                    id: 2,
                    text: '测试阶段',
                    start_date: '2025-07-05',
                    end_date: '2025-07-15',
                    actual_start: '2025-07-07',
                    actual_end: '2025-07-17',
                    parent: 1
                }
            ]
        })
    })

    onBeforeUnmount(() => {
        gantt.clearAll()
    })
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
</style>
